/*
   Copyright 2009 Bloo. All Rights Reserved.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
package org.youtensils.www.client.widgets;

import org.youtensils.www.client.resources.GlobalImages;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TabPanel;
import com.google.gwt.user.client.ui.Widget;

/**
 * A tab widget that supports closing.
 * @author Bobby Soares
 */
public class ClosableTab extends Composite {
	private FlexTable contentPane;
	private TabPanel tabPanel;
	private Widget widget;
	/**
	 * A constructor specifying the tab label, the Tab widget to build upon and the TabPanel widget into which the tab should be added.
	 * @param text
	 * @param widget
	 * @param tabPanel
	 */
	public ClosableTab(String text, Widget widget, TabPanel tabPanel){
		this.tabPanel = tabPanel;
		this.widget = widget;
		this.contentPane = new FlexTable();
		this.contentPane.setWidth("100%");
		this.contentPane.setCellPadding(0);
		this.contentPane.setCellSpacing(0);
		this.contentPane.insertRow(0);
		this.contentPane.insertCell(0, 0);
		this.contentPane.insertCell(0, 1);
		this.contentPane.getCellFormatter().setWidth(0, 1, "20px");
		Label label = new Label();
		label.setWordWrap(false);
		label.setText(text);
		Image close = GlobalImages.images.CloseGeneric().createImage();
		close.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				ClosableTab.this.tabPanel.remove(ClosableTab.this.widget);
				if(ClosableTab.this.tabPanel.getTabBar().getTabCount() > 0){
					ClosableTab.this.tabPanel.selectTab(0);
				}
			}
		});
		close.setStylePrimaryName("gwt-ClosableTab-Icon");
		this.contentPane.setWidget(0, 0, label);
		this.contentPane.setWidget(0, 1, close);
    	initWidget(contentPane);
    	setStyleName("gwt-ClosableTab");
		tabPanel.add(widget, this);
	}
}
